//
//  CXHUBiMAXNativeAdapter.m
//  CXHAdSDK-UBiMAX
//
//  Created by 陈坤 on 2025/7/28.
//

#import "CXHUBiMAXNativeAdapter.h"
#import "CXHUBiMAXNativeAd.h"
#import "CXHUBiMAXNativeExpressAd.h"
#import <UBiMAXAdSDK/UBiMAXAdSDK-umbrella.h>
#import <CXHAdSDK-Adapter/CXHAdapterNativeExpressCallBack.h>
#import <CXHAdSDK-Adapter/CXHAdapterNativeAdViewDelegate.h>
#import <CXHAdSDK-Kit/CXHUtilsKit.h>

@interface CXHUBiMAXNativeAdapter ()<UMTCustomNativeAdapter, CXHUBiMAXNativeAdDelegate, CXHUBiMAXNativeExpressAdDelegate>

@property (nonatomic, strong) CXHUBiMAXNativeAd *nativeAd;

@property (nonatomic, strong) CXHUBiMAXNativeExpressAd *nativeExpressAd;

@property (nonatomic, assign) UMTAdBidType umtBidType;
@property (nonatomic, assign) UMTVideoMuteType umtVideoMuteType;

@end

@implementation CXHUBiMAXNativeAdapter

- (UMTMediatedAdStatus)mediatedAdStatus {
    if (self.nativeAd) {
        return UMTMediatedAdStatusNormal;
    } else if (self.nativeExpressAd) {
        return UMTMediatedAdStatusNormal;
    }
    return UMTMediatedAdStatusUnknown;
}

/// 加载广告的方法
/// @param slotID adn的广告位ID
/// @param size 广告展示尺寸
/// @param imageSize 图片或视频展示尺寸
/// @param parameter 广告加载的参数
- (void)loadNativeAdWithSlotID:(NSString *)slotID andSize:(CGSize)size imageSize:(CGSize)imageSize parameter:(NSDictionary *)parameter {
    NSNumber *bidType = parameter[UMTAdLoadingParamBiddingType];
    self.umtBidType = (UMTAdBidType)bidType.integerValue;
    NSNumber *videoMuteNum = parameter[UMTAdLoadingParamVideoMute];
    self.umtVideoMuteType = (UMTVideoMuteType)videoMuteNum.integerValue;

    NSNumber *renderTypeNum = parameter[UMTAdLoadingParamRenderType];
    if ((UMTAdRenderType)renderTypeNum.integerValue == UMTAdRenderType_Temple) {
        if (self.nativeExpressAd) {
            self.nativeExpressAd.delegate = nil;
            self.nativeExpressAd = nil;
        }
        CXHAdSDKNativeExpressType expressType = CXHAdSDKNativeExpressTypeImage;
        BOOL showCloseView = NO;
        NSString *jsonStr = parameter[UMTAdLoadingParamExtJson];
        if (!kCXHStringIsEmpty(jsonStr)) {
            //json解析
            NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
            if (jsonData) {
                NSError *err;
                       
                NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData
                                                                         options:NSJSONReadingMutableContainers
                                                                           error:&err];
                
                if (err == nil && !kCXHDictIsEmpty(jsonDict)) {
                    NSString *str = [jsonDict CXH_objectOrNilForKey:@"showCloseView"];
                    if (!kCXHStringIsEmpty(str) && [str isEqualToString:@"true"]) {
                        showCloseView = YES;
                    }
                    NSString *expressConfigType = [jsonDict CXH_objectOrNilForKey:@"expressType"];
                    if (!kCXHStringIsEmpty(expressConfigType)) {
                        if ([expressConfigType isEqualToString:@"left"]) {
                            expressType = CXHAdSDKNativeExpressTypeLeft;
                        }
                        if ([expressConfigType isEqualToString:@"vimage"]) {
                            expressType = CXHAdSDKNativeExpressTypeVerticalImage;
                        }
                    }
                }
            }
        }
        self.nativeExpressAd = [[CXHUBiMAXNativeExpressAd alloc] init];
        self.nativeExpressAd.delegate = self;
        [self.nativeExpressAd loadNativeExpressAd:slotID size:size controller:self.bridge.viewControllerForPresentingModalView count:1 showCloseView:showCloseView expressType:expressType];
        return;
    }
    NSError *err = [[NSError alloc] initWithDomain:@"com.ubixai.umtd.cxh"
                                              code:-2
                                          userInfo:@{NSLocalizedDescriptionKey: @"暂不支持信息流自渲染"}];
    [self.bridge nativeAd:self didLoadFailWithError:err];
    // 暂不支持自渲染
//    if (self.nativeAd) {
//        self.nativeAd.delegate = nil;
//        self.nativeAd = nil;
//    }
//    
//    self.nativeAd = [[CXHUBiMAXNativeAd alloc] init];
//    self.nativeAd.delegate = self;
//    
//    [self.nativeAd loadNativeAd:slotID controller:self.bridge.viewControllerForPresentingModalView count:1];
}

/// 渲染广告，为非模板广告时会回调该方法
- (void)renderView:(UMTNativeAdView *)nativeAdView selfRenderView:(nonnull UIView *)selfRenderView {
//    UMTMediationNativeAd *mNativeAd = nativeAdView.native;
//    if ([mNativeAd.originMediatedNativeAd isKindOfClass:[KSNativeAd class]]) {
//        KSNativeAd *ksNativeAd = mNativeAd.originMediatedNativeAd;
//        
//        if (ksNativeAd.data.materialType == KSAdMaterialTypeVideo) {
//            // 静音
//            KSVideoAdView *videoView = self.ksNativeHelper.relatedView.videoAdView;
//            switch (self.umtVideoMuteType) {
//                case UMTVideoMuteType_Mute:
//                    videoView.videoSoundEnable = NO;
//                    break;
//                case UMTVideoMuteType_NoMute:
//                    videoView.videoSoundEnable = YES;
//                    break;
//                    
//                default:
//                    break;
//            }
//            
//        }
//    }
}

/// 为非模板广告设置控制器
/// @param viewController 控制器
/// @param nativeAd 非模板广告
- (void)setRootViewController:(UIViewController *)viewController forNativeAd:(UMTMediationNativeAd *)nativeAd {
//    KSNativeAd *ksNativeAd = nativeAd.originMediatedNativeAd;
//    ksNativeAd.rootViewController = viewController;
}

/// 注册容器和可点击区域
/// @param containerView 容器视图
/// @param views 可点击视图组
- (void)registerContainerView:(__kindof UIView *)containerView andClickableViews:(NSArray<__kindof UIView *> *)views closableViews:(NSArray *)closableViews forNativeAd:(UMTMediationNativeAd *)nativeAd {
//    if ([nativeAd.originMediatedNativeAd isKindOfClass:[KSNativeAd class]]) {
//        KSNativeAd *adDataObj = (KSNativeAd *)nativeAd.originMediatedNativeAd;
//        
//        KSNativeAdRelatedView *relatedView = self.ksNativeHelper.relatedView;
//        [relatedView refreshData:adDataObj];
//        [relatedView.videoAdView setVideoSoundEnable:NO];
//        
//        [adDataObj registerContainer:containerView withClickableViews:views containerClickable:YES];
//        
//        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeTapAction:)];
//        for (UIView *v in closableViews) {
//            [v addGestureRecognizer:tap];
//        }
//    }
}

- (void)renderForExpressAdView:(UIView *)expressAdView { 
    UIView<CXHAdapterNativeExpressAdViewDelegate> *adView = (UIView<CXHAdapterNativeExpressAdViewDelegate> *)expressAdView;
    [adView render];
}


- (void)setRootViewController:(UIViewController *)viewController forExpressAdView:(UIView *)expressAdView {
    UIView<CXHAdapterNativeExpressAdViewDelegate> *adView = (UIView<CXHAdapterNativeExpressAdViewDelegate> *)expressAdView;
    [adView cxh_setRootViewController:viewController];
}


- (void)didReceiveBidResult:(UMTMediaBidResult *)result {
    // 在此处理Client Bidding的结果回调
    if (result.win) {
        if (self.nativeAd) {
            NSInteger winPrice = self.nativeAd.getBidPrice;
            if (result.winnerPrice) {
                winPrice = result.winnerPrice;
            }
            [self.nativeAd sendWinNotice:winPrice];
        }
        if (self.nativeExpressAd) {
            NSInteger winPrice = self.nativeExpressAd.getBidPrice;
            if (result.winnerPrice) {
                winPrice = result.winnerPrice;
            }
            [self.nativeExpressAd sendWinNotice:winPrice];
        }
    } else {
        if (result.winnerPrice) {
            if (self.nativeAd) {
                [self.nativeAd sendLossNotice:result.winnerPrice];
            }
            if (self.nativeExpressAd) {
                [self.nativeExpressAd sendLossNotice:result.winnerPrice];
            }
        }
    }
}

- (void)destroyAd { 
    
}

#pragma mark - CXHUBiMAXNativeExpressAdDelegate
/**
 信息流广告请求成功

 @param nativeExpressAd 广告实例
 @param adViewArray 广告模板集合
 */
- (void)CXHUBiMAX_nativeExpressAdSucessToLoad:(CXHAdSDKNativeExpressAd *)nativeExpressAd
                                   adViewArray:(NSArray<__kindof UIView<CXHAdapterNativeExpressAdViewDelegate> *> *)adViewArray{
    
    NSMutableArray *exts = [NSMutableArray array];
    for (UIView<CXHAdapterNativeExpressAdViewDelegate> *adView in adViewArray) {
        NSMutableDictionary *extDic = [NSMutableDictionary dictionary];
        if (self.umtBidType == UMTAdBidType_ClientBidding) {
            NSInteger price = nativeExpressAd.getBidPrice;
            if (price>0) {
                [extDic setValue:[NSString stringWithFormat:@"%ld", (long)price] forKey:UMTAdnAdLoadedExtECPM];
                
            }
        }
        
        [exts addObject: extDic];
    }

    [self.bridge nativeAd:self didLoadWithExpressViews:[adViewArray copy] exts:exts.copy];
}

/**
 信息流广告请求失败

 @param nativeExpressAd 广告实例
 @param error 请求错误描述
 */
- (void)CXHUBiMAX_nativeExpressAdFailToLoad:(CXHAdSDKNativeExpressAd *)nativeExpressAd
                                       error:(NSError *)error{
    [self.bridge nativeAd:self didLoadFailWithError:error];
}

/**
 信息流广告渲染成功

 @param adView 广告视图
 */
- (void)CXHUBiMAX_nativeExpressAdViewRenderOrRegistSuccess:(CXHAdSDKNativeExpressAd *)nativeExpressAd adView:(UIView<CXHAdapterNativeExpressAdViewDelegate> *)adView{
    [self.bridge nativeAd:self renderSuccessWithExpressView:adView];
//    NSLog(@"===height4===%f",adView.frame.size.height);
}

/**
 信息流广告渲染失败

 @param adView 广告视图
 */
- (void)CXHUBiMAX_nativeExpressAdViewRenderOrRegistFail:(CXHAdSDKNativeExpressAd *)nativeExpressAd adView:(UIView<CXHAdapterNativeExpressAdViewDelegate> *)adView{
    
}

/**
 信息流广告被点击

 @param nativeExpressAd 广告模板
 */
- (void)CXHUBiMAX_nativeExpressAdClicked:(CXHAdSDKNativeExpressAd *)nativeExpressAd
                                   adView:(__kindof UIView<CXHAdapterNativeExpressAdViewDelegate> *)adView loadingPageURL:(NSString *)loadingPageURL{
    
    [self.bridge nativeAd:self didClickWithMediatedNativeAd:adView];
    [self.bridge nativeAd:self willPresentFullScreenModalWithMediatedNativeAd:adView];
    
}

/**
 信息流广告被关闭
 
 @param nativeExpressAd 广告模板
 */
- (void)CXHUBiMAX_nativeExpressAdClose:(CXHAdSDKNativeExpressAd *)nativeExpressAd
                                 adView:(__kindof UIView<CXHAdapterNativeExpressAdViewDelegate> *)adView{
    
    [self.bridge nativeAd:self didCloseWithExpressView:adView closeReasons:@[]];
}

/**
 信息流广告被展示
 
 @param nativeExpressAd 广告实例
 */
- (void)CXHUBiMAX_nativeExpressAdExposure:(CXHAdSDKNativeExpressAd *)nativeExpressAd
                                    adView:(__kindof UIView<CXHAdapterNativeExpressAdViewDelegate> *)adView{
    [self.bridge nativeAd:self didVisibleWithMediatedNativeAd:adView];
}

/**
 信息流广告展示上报
 
 @param nativeExpressAd 广告实例
 */
- (void)CXHUBiMAX_nativeExpressAdExposureReport:(CXHAdSDKNativeExpressAd *)nativeExpressAd
                                          adView:(__kindof UIView<CXHAdapterNativeExpressAdViewDelegate> *)adView{
    
}

/**
 信息流广告点击上报

 @param nativeExpressAd 广告模板
 */
- (void)CXHUBiMAX_nativeExpressAdClickedReport:(CXHAdSDKNativeExpressAd *)nativeExpressAd
                                         adView:(__kindof UIView<CXHAdapterNativeExpressAdViewDelegate> *)adView{
}

/**
 信息流广告落地页被关闭
 
 @param nativeExpressAd 广告实例
 */
- (void)CXHUBiMAX_nativeExpressAdCloseLandingPage:(CXHAdSDKNativeExpressAd *)nativeExpressAd
                                            adView:(__kindof UIView<CXHAdapterNativeExpressAdViewDelegate> *)adView{
    [self.bridge nativeAd:self willPresentFullScreenModalWithMediatedNativeAd:adView];
}



@end
